package commSql

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntity"
	"time"
)

func Query(entityType string, sql string) ([]commEntity.IEntity, error) {
	return Client.Query(entityType, sql)
}

func SQuery(entityType string, sql string, args []interface{}) ([]commEntity.IEntity, error) {
	return Client.SQuery(entityType, sql, args)
}

func SQueryCount(sql string, args []interface{}) (int, error) {
	return Client.SQueryCount(sql, args)
}

func QueryCount(sql string) (int, error) {
	return Client.QueryCount(sql)
}

func QueryEntityList(entityType string) ([]commEntity.IEntity, error) {
	sql, err := SQL.Select(entityType)
	if err != nil {
		return nil, err
	}
	return Client.Query(entityType, sql)
}

func QueryEntityById(entityType string, id int64) (commEntity.IEntity, error) {
	sql, err := SQL.SelectWhereId(entityType, id)
	if err != nil {
		return nil, err
	}

	list, err := Client.Query(entityType, sql)
	if err != nil {
		return nil, err
	}

	if list == nil || len(list) < 1 {
		return nil, nil
	}

	return list[0], nil
}

func InsertRecord(tableName string, entity commEntity.IEntity) error {
	// 写入时间
	now := time.Now().UnixMilli()
	entity.GetBaseEntity().CreateTime = now
	entity.GetBaseEntity().UpdateTime = now

	sql, values, err := SQL.InsertRecord(tableName, entity)
	if err != nil {
		return err
	}

	// 执行SQL语句
	id, err := Client.Exec(sql, values)
	if err != nil {
		return err
	}

	// 写入基础信息
	baseEntity := entity.GetBaseEntity()
	baseEntity.Id = id
	return nil
}

func InsertEntity(entity commEntity.IEntity) error {
	return InsertRecord(entity.TableName(), entity)
}

func UpdateEntityById(entity commEntity.IEntity) error {
	return UpdateRecordById(entity.TableName(), entity)
}

func UpdateRecordById(tableName string, entity commEntity.IEntity) error {
	// 写入时间
	now := time.Now().UnixMilli()
	entity.GetBaseEntity().UpdateTime = now

	sql, values, err := SQL.UpdateWhereId(entity)
	if err != nil {
		return err
	}

	// 执行SQL语句
	_, err = Client.Exec(sql, values)
	if err != nil {
		return err
	}

	return nil
}

func DeleteEntityById(entityType string, id int64) error {
	sql, err := SQL.DeleteWhereId(entityType, id)
	if err != nil {
		return err
	}

	_, err = Client.Exec(sql, nil)
	if err != nil {
		return err
	}

	return nil
}

func HasSchema(entityType string) bool {
	return schema.hasSchema(entityType)
}
